package com.sczmgk.track.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.sczmgk.track.constant.Constant;
import com.sczmgk.track.utils.CacheUtils;
import com.sczmgk.track.utils.MyLog;


public class ListenNetStateReceiver extends BroadcastReceiver {

	private final String TAG = ListenNetStateReceiver.class.getSimpleName();
	private ConnectivityManager connectivityManager;
	private NetworkInfo info;

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
			MyLog.d(TAG, "网络状态已经改变");
			connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
					
			info = connectivityManager.getActiveNetworkInfo();
			if (info != null && info.isAvailable()) {
				String name = info.getTypeName();
				if(onNetWorkChangedListener != null){
					onNetWorkChangedListener.onConnedted();
				}
				MyLog.d(TAG, "当前网络名称：" + name);
			} else {
				MyLog.d(TAG, "没有可用网络");
				CacheUtils.cacheBooleanData(context, Constant.IS_DISCONNECTION_NETWORK, true);
				boolean isDisconnection = CacheUtils.getBooleanData(context, Constant.IS_DISCONNECTION_NETWORK, false);
				MyLog.i(TAG,"缓存断开的状态： "+isDisconnection);
				if(onNetWorkChangedListener != null){
					onNetWorkChangedListener.onDisconnected();
				}
			}
		}
	}
	public static OnNetWorkChangedListener onNetWorkChangedListener;

	public interface OnNetWorkChangedListener{
		void onDisconnected();
		void onConnedted();
	}
}
